package com.xc.erp.modules.erp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xc.erp.modules.erp.domain.TreeSelect;
import com.xc.erp.modules.erp.domain.pojo.JshOrganization;
import com.xc.erp.modules.erp.service.JshOrganizationService;
import com.xc.erp.modules.erp.mapper.JshOrganizationMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class JshOrganizationServiceImpl extends ServiceImpl<JshOrganizationMapper, JshOrganization>
    implements JshOrganizationService{

    @Override
    public List<TreeSelect> buildTreeSelect() {
        List<JshOrganization> organizationsTree = childTreeDept();
        return organizationsTree.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    public List<JshOrganization> childTreeDept() {
        List<JshOrganization> rootTree = new ArrayList<>();
        List<JshOrganization> organizationList = this.baseMapper.selectList(null);
        for (JshOrganization organization : organizationList) {
            if (organization.getParentId() == 0) {
                rootTree.add(organization);
            }
        }

        for (JshOrganization organization : rootTree) {
            List<JshOrganization> chileList = getChild(organization.getId(), organizationList);
            organization.setChildren(chileList);
        }

        return rootTree;

    }

    private List<JshOrganization> getChild(Long id, List<JshOrganization> jshOrganizations) {
        //子菜单
        List<JshOrganization> childList = new ArrayList<>();
        for (JshOrganization organization : jshOrganizations) {
            if (organization.getParentId().equals(id)) {
                childList.add(organization);
            }
        }

        for (JshOrganization organization : childList) {
            organization.setChildren(getChild(organization.getId(), jshOrganizations));
        }

        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }
}




